package com.atguigu.gulimall.product.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.*;
import com.atguigu.gulimall.product.config.OssProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class OssUtil {


    /**
     * 此处url无法直接浏览器预览，还需要配置域名
     */
    public static String upload(MultipartFile file) {
        String url = null;
        if (file.isEmpty()) {
            throw new ServiceException("上传文件不能为空");
        }
        /*if (!checkFileSize(file.getSize(), BaseConstant.LEN, BaseConstant.UNIT_M)) {
            throw new ServiceException("上传文件大小不能超过10M");
        }*/
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
        //判断oss实例是否存在：如果不存在则创建，如果存在则获取
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)) {
            //创建bucket
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            //log.info("bucket存储空间【{}】创建成功", OssProperties.BUCKET_NAME);
            //设置oss实例的访问权限：公共读
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
            //log.info("【{}】存储空间访问权限设置为公共读成功");
        }
        // 上传文件流。
        // 保存路径 文件名 ，注意：这里不要以 / 或 \ 开头
        String path = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String originalFilename = file.getOriginalFilename();
        String fileName = path + "/" + UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            /*V3.0.1 解决阿里云OSS 打开图片地址无法预览,直接下载*/
            ObjectMetadata meta = new ObjectMetadata();
            //指定了图片格式
            //meta.setContentType("image/jpg");
            meta.setContentType(getcontentType(originalFilename.substring(originalFilename.lastIndexOf("."))));
            //设置文件权限为 公共读
            meta.setObjectAcl(CannedAccessControlList.PublicRead);
            meta.setContentDisposition("inline");
            //PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            PutObjectRequest putObjectRequest = new PutObjectRequest(OssProperties.BUCKET_NAME, fileName, file.getInputStream(), meta);
            putObjectRequest.setProcess("true");
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            // 获取url地址（根据阿里云oss中的图片实例拼接字符串） 拼接url字符串
            // https://edu-leader.oss-cn-beijing.aliyuncs.com/%E4%BB%96.jpg
            url = "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/"+fileName;
            System.out.println(url);
            String uri = putObjectResult.getResponse().getUri();
            System.out.println(uri);
        } catch (IOException e) {
            throw new ServiceException("上传失败" + e.getMessage());
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return url;
    }

    //通过该方法快速获取文件类型
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }

}
